<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { Logic } from './Logic.js';

const emits = defineEmits(['stage']);
const props = defineProps({
  mapdata: { type: Object, required: true },
});

let logic;
let editorRef = ref(null);

onMounted(() => {
  logic = new Logic(editorRef.value);
  logic.observer.addListener('stage', (...args) => emits('stage', ...args));
  logic.observer.addListener('loaded', () => emits('stage', { stage: null }));
  logic.observer.addListener('zoomend', () => onUpdate());
  logic.observer.addListener('dragend', () => onUpdate());
  props.mapdata.addListener('data', (data) => logic.load(data));
});

onUnmounted(() => {
  logic && logic.destroy();
});

/** @事件 更新拖动偏移量和缩放比例 */
let requestId;
function onUpdate() {
  requestId && clearTimeout(requestId);
  requestId = setTimeout(() => {
    const data = props.mapdata.data;
    data.background.offsetX = logic.parser.background.offsetX;
    data.background.offsetY = logic.parser.background.offsetY;
    data.scale.scaling = logic.parser.scale.scaling;
    props.mapdata.dispatch('data', data);
  }, 100);
}
</script>

<template>
  <div class="MapViewer" ref="editorRef"></div>
</template>

<!-- 允许自定义宽高通过CSS进行控制 -->
<style scoped>
.MapViewer {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: gray;
}
</style>